﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Twinkle.Tweak;
using Krile.Kernel;

namespace Twinkle.Dialogs.Account
{
    public partial class AccountEditor : Form
    {
        public Data.Account Account { get; private set; }
        public AccountEditor()
        {
            InitializeComponent();
            Account = null;
        }

        public AccountEditor(Data.Account a)
            : this()
        {
            Account = a;
        }

        private void AccountEditor_Load(object sender, EventArgs e)
        {
            if (Account == null)
            {
                throw new InvalidOperationException("Account editor can't call with NULL account.");
            }
            if (String.IsNullOrEmpty(Account.UserId))
            {
                using (var oauth = new OAuthRequest(Account))
                {
                    if (oauth.ShowDialog() != DialogResult.OK)
                    {
                        this.DialogResult = DialogResult.Cancel;
                        this.Close();
                    }
                }
            }
            authAsName.Text = Account.UserId;
            if (Account.UpdatesDinamically)
                dynamicUpdateRadio.Checked = true;
            else
                staticUpdateRadio.Checked = true;

            dynamicApiUseTrack.Value = Account.ApiUseLimit;
            dynamicNormalTrack.Value = Account.HomeTimelineReceivePercent;
            dynamicReplyTrack.Value = Account.ReplyFeedReceivePercent;
            dynamicDMTrack.Value = Account.DMReceivePercent;
            dynamicListTrack.Value = Account.ListReceivePercent;

            useUserStreams.Checked = Account.UseUserStreams;

            staticNormalNumeric.Value = Account.HomeTimelineReceiveInterval;
            staticReplyNumeric.Value = Account.ReplyFeedReceiveInterval;
            staticDMNumeric.Value = Account.DMReceiveInterval;
            staticListNumeric.Value = Account.ListReceiveInterval;

            usePostSignature.Checked = Account.UseSignature;
            postSignature.Text = Account.Signature;

            RefreshListLists();
        }

        private void doReAuth_Click(object sender, EventArgs e)
        {
            using (var oauth = new OAuthRequest(Account))
            {
                if (oauth.ShowDialog() == DialogResult.OK)
                {
                    authAsName.Text = Account.UserId;
                }
            }
        }

        private void dynamicApiUseTrack_ValueChanged(object sender, EventArgs e)
        {
            dynamicApiUseLabel.Text = dynamicApiUseTrack.Value.ToString();
        }

        private void dynamicNormalTrack_ValueChanged(object sender, EventArgs e)
        {
            dynamicNormalLabel.Text = dynamicNormalTrack.Value.ToString();
        }

        private void dynamicReplyTrack_ValueChanged(object sender, EventArgs e)
        {
            dynamicReplyLabel.Text = dynamicReplyTrack.Value.ToString();
        }

        private void dynamicDMTrack_ValueChanged(object sender, EventArgs e)
        {
            dynamicDMLabel.Text = dynamicDMTrack.Value.ToString();
        }

        private void dynamicListTrack_ValueChanged(object sender, EventArgs e)
        {
            dynamicListLabel.Text = dynamicListTrack.Value.ToString();
        }

        private void updateMethodCheckedChanged(object sender, EventArgs e)
        {
            dynamicUpdateGroup.Enabled = dynamicUpdateRadio.Checked;
            staticUpdateGroup.Enabled = staticUpdateRadio.Checked;
        }

        private void okBtn_Click(object sender, EventArgs e)
        {
            Account.UserId = authAsName.Text;
            Account.UpdatesDinamically = dynamicUpdateRadio.Checked;

            Account.ApiUseLimit = dynamicApiUseTrack.Value;
            Account.HomeTimelineReceivePercent = dynamicNormalTrack.Value;
            Account.ReplyFeedReceivePercent = dynamicReplyTrack.Value;
            Account.DMReceivePercent = dynamicDMTrack.Value;
            Account.ListReceivePercent = dynamicListTrack.Value;

            Account.UseUserStreams = useUserStreams.Checked;

            Account.HomeTimelineReceiveInterval = (int)staticNormalNumeric.Value;
            Account.ReplyFeedReceiveInterval = (int)staticReplyNumeric.Value;
            Account.DMReceiveInterval = (int)staticDMNumeric.Value;
            Account.ListReceiveInterval = (int)staticListNumeric.Value;

            Account.UseSignature = usePostSignature.Checked;
            Account.Signature = postSignature.Text;
            
            var rrl = from i in receiveLists.Items.OfType<string>()
                      select i;
            Account.ReceiveReservedLists = rrl.ToArray();

            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void listRefresh_Click(object sender, EventArgs e)
        {
            using (var liu = new ListInformationUpdate(Account))
            {
                liu.ShowDialog(this);
            }
            foreach (var l in Account.FollowingLists)
            {
                System.Diagnostics.Debug.WriteLine("::" + l.Id + ":");
                if (l.Members != null)
                    System.Diagnostics.Debug.WriteLine(String.Join(Environment.NewLine, l.Members));
                else
                    System.Diagnostics.Debug.WriteLine("Member data is NULL.");
            }
            RefreshListLists();
        }

        private void RefreshListLists()
        {
            followingLists.Items.Clear();
            receiveLists.Items.Clear();
            if (Account.FollowingLists != null && Account.FollowingLists.Length > 0)
            {
                followingLists.Items.AddRange(Account.FollowingLists);

                if (Account.ReceiveReservedLists != null && Account.ReceiveReservedLists.Length > 0)
                {
                    foreach (var r in Account.ReceiveReservedLists)
                    {
                        bool f = false;
                        foreach (var fl in Account.FollowingLists)
                        {
                            if ("@" + fl.ParentUserId + "/" + fl.Id == r)
                            {
                                f = true;
                                break;
                            }
                        }
                        if (!f)
                            continue;
                        receiveLists.Items.Add(r);
                    }
                }
            }
        }

        private void listAdd_Click(object sender, EventArgs e)
        {
            if (followingLists.SelectedIndex >= 0 && followingLists.SelectedIndex < followingLists.Items.Count)
            {
                var item = followingLists.Items[followingLists.SelectedIndex] as TList;
                if (item == null)
                {
                    MessageBox.Show("Error:invalid cast");
                    return;
                }
                if (receiveLists.Items.Contains(item.ToString()))
                    return;
                receiveLists.Items.Add(item.ToString());
            }
        }

        private void followingLists_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            listAdd_Click(null, null);
        }

        private void listDelete_Click(object sender, EventArgs e)
        {
            if (receiveLists.SelectedIndex >= 0 && receiveLists.SelectedIndex < receiveLists.Items.Count)
            {
                receiveLists.Items.RemoveAt(receiveLists.SelectedIndex);
            }
        }

        private void listClearAll_Click(object sender, EventArgs e)
        {
            Account.ReceiveReservedLists = null;
            receiveLists.Items.Clear();
        }

        private void createTab_Click(object sender, EventArgs e)
        {
            if (followingLists.SelectedIndex >= 0 && followingLists.SelectedIndex < followingLists.Items.Count)
            {
                var item = followingLists.Items[followingLists.SelectedIndex] as TList;
                if (item == null)
                {
                    MessageBox.Show("Error:invalid cast");
                    return;
                }
                Bridge.MainForm.AddTab(
                    "Twitter list:@" + item.ParentUserId + "/" + item.Id,
                    new Krile.Kernel.Data.SearchDataCluster()
                    {
                        SearchDatas = new Krile.Kernel.Data.SearchData[]{
                            new Searchs.SearchTwitterStatus(),   
                            new Searchs.SearchTwitterListedStatus(){ ListId = item.Id, ParentAccountId = item.ParentUserId}
                        }
                    }, new[] { Define.ServiceId });
            }
        }
    }
}
